<template>
  <div class="dashboard-container">
    <!-- github 角标 -->
    <github-corner class="github-corner" />

    <el-card shadow="never" class="mt-2">
      <el-row class="h-80px">
        <el-col :span="18" :xs="24">
          <div class="flex-x-start">
            <img
              class="w80px h80px rounded-full"
              :src="userStore.userInfo.avatar + '?imageView2/1/w/80/h/80'"
            />
            <div class="ml-5">
              <p>{{ greetings }}</p>
              <p class="text-sm text-gray">今日天气晴朗，气温在15℃至25℃之间，东南风。</p>
            </div>
          </div>
        </el-col>

<!--        <el-col :span="6" :xs="24">
          <el-row class="h-80px flex-y-center" :gutter="10">
            <el-col :span="10">
              <div class="font-bold color-#ff9a2e text-sm flex-y-center">
                <el-icon class="mr-2px"><Folder /></el-icon>
                仓库
              </div>
              <div class="mt-3">
                <el-link href="https://gitee.com/youlaiorg/vue3-element-admin" target="_blank">
                  <div class="i-svg:gitee text-lg color-#F76560" />
                </el-link>
                <el-divider direction="vertical" />
                <el-link href="https://github.com/youlaitech/vue3-element-admin" target="_blank">
                  <div class="i-svg:github text-lg color-#4080FF" />
                </el-link>
                <el-divider direction="vertical" />
                <el-link href="https://gitcode.com/youlai/vue3-element-admin" target="_blank">
                  <div class="i-svg:gitcode text-lg color-#FF9A2E" />
                </el-link>
              </div>
            </el-col>

            <el-col :span="10">
              <div class="font-bold color-#4080ff text-sm flex-y-center">
                <el-icon class="mr-2px"><Document /></el-icon>
                文档
              </div>
              <div class="mt-3">
                <el-link href="https://juejin.cn/post/7228990409909108793" target="_blank">
                  <div class="i-svg:juejin text-lg" />
                </el-link>
                <el-divider direction="vertical" />
                <el-link
                  href="https://youlai.blog.csdn.net/article/details/130191394"
                  target="_blank"
                >
                  <div class="i-svg:csdn text-lg" />
                </el-link>
                <el-divider direction="vertical" />
                <el-link href="https://www.cnblogs.com/haoxianrui/p/17331952.html" target="_blank">
                  <div class="i-svg:cnblogs text-lg" />
                </el-link>
              </div>
            </el-col>

            <el-col :span="4">
              <div class="font-bold color-#f76560 text-sm flex-y-center">
                <el-icon class="mr-2px"><VideoCamera /></el-icon>
                视频
              </div>
              <div class="mt-3">
                <el-link href="https://www.bilibili.com/video/BV1eFUuYyEFj" target="_blank">
                  <div class="i-svg:bilibili text-lg" />
                </el-link>
              </div>
            </el-col>
          </el-row>
        </el-col>-->
      </el-row>
    </el-card>

    <!-- 家谱地图 -->
    <el-card shadow="never" class="mt-5">
      <template #header>
        <div class="flex-x-between">
          <span class="font-bold">李氏家谱分布地图</span>
          <div class="map-controls">
            <el-select v-model="selectedRegion" placeholder="选择地区" size="default" @change="onRegionChange" class="region-select">
              <el-option 
                v-for="item in regionOptions" 
                :key="item.value" 
                :label="item.label" 
                :value="item.value"
              />
            </el-select>
            <el-radio-group v-model="mapViewType" size="default" class="view-type-radio">
              <el-radio-button label="热力图" value="heatmap" />
              <el-radio-button label="标记点" value="marker" />
            </el-radio-group>
          </div>
        </div>
      </template>
      <div id="genealogy-map" class="map-container"></div>
    </el-card>
  </div>
</template>

<script setup>
defineOptions({
  name: "Dashboard",
  inheritAttrs: false,
});

import { useUserStore } from "@/store/modules/user.store";
import { onMounted, ref, computed, watch, onBeforeUnmount } from 'vue';
import FamilyAPI from "@/api/genealogy/family.api";

const userStore = useUserStore();

// 地图相关配置
const mapViewType = ref('marker'); // 地图视图类型：热力图/标记点
let amapInstance = null; // 高德地图实例
let heatmapInstance = null; // 热力图实例

// 家谱数据
const genealogyData = ref([]);

// 获取家谱数据
const fetchGenealogyData = async () => {
  try {
    const response = await FamilyAPI.getPage({
      pageNum: 1,
      pageSize: 100 // 获取足够多的数据以显示在地图上
    });
    
    // 转换数据格式以适配地图显示
    genealogyData.value = response.list.map(item => ({
      id: item.id,
      name: item.familyName,
      regionCode: item.areaCode ? item.areaCode.substring(0, 6) : '',
      regionName: item.mergerName,
      location: [parseFloat(item.lng), parseFloat(item.lat)],
      count: item.nums || 0, // 每个家谱的在世成员数量
      date: item.updateTime,
      description: `${item.familyName} - ${item.originPlace} - ${item.totem}`
    }));
    console.log(genealogyData.value);
    // 如果有地图实例，更新地图显示
    if (amapInstance) {
      renderMapByViewType();
    }
  } catch (error) {
    console.error('获取家谱数据失败:', error);
  }
};

// 地区选项
const regionOptions = ref([
  { value: 'all', label: '全部地区' },
  { value: '360102', label: '南昌市' },
  { value: '360202', label: '景德镇市' },
  { value: '360302', label: '萍乡市' },
  { value: '360402', label: '九江市' },
  { value: '360502', label: '新余市' },
  { value: '360602', label: '鹰潭市' },
  { value: '360702', label: '赣州市' },
  { value: '360802', label: '吉安市' },
  { value: '360902', label: '宜春市' },
  { value: '361002', label: '抚州市' },
  { value: '361102', label: '上饶市' }
]);

// 当前选中的地区
const selectedRegion = ref('all');

// 当前时间（用于计算问候语）
const currentDate = new Date();

// 问候语：根据当前小时返回不同问候语
const greetings = computed(() => {
  const hours = currentDate.getHours();
  const nickname = userStore.userInfo.nickname;
  if (hours >= 6 && hours < 8) {
    return "晨起披衣出草堂，轩窗已自喜微凉🌅！";
  } else if (hours >= 8 && hours < 12) {
    return `上午好，${nickname}！`;
  } else if (hours >= 12 && hours < 18) {
    return `下午好，${nickname}！`;
  } else if (hours >= 18 && hours < 24) {
    return `晚上好，${nickname}！`;
  } else {
    return "偷偷向银河要了一把碎星，只等你闭上眼睛撒入你的梦中，晚安🌛！";
  }
});

// 根据选择的地区获取筛选后的家谱数据
const getFilteredGenealogyData = () => {
  if (selectedRegion.value === 'all') {
    return genealogyData.value;
  } else {
    return genealogyData.value.filter(item => item.regionCode === selectedRegion.value);
  }
};

// 加载高德地图脚本
const loadAMapScript = () => {
  return new Promise((resolve, reject) => {
    // 检查是否已加载
    if (window.AMap) {
      resolve(window.AMap);
      return;
    }
    
    const script = document.createElement('script');
    script.type = 'text/javascript';
    script.async = true;
    script.src = 'https://webapi.amap.com/maps?v=2.0&key=8719566e0008eef16d17c687ed31e2b8&plugin=AMap.HeatMap';
    script.onerror = reject;
    script.onload = () => {
      resolve(window.AMap);
    };
    document.head.appendChild(script);
  });
};

// 初始化地图
const initMap = async () => {
  try {
    await loadAMapScript();
    
    amapInstance = new AMap.Map('genealogy-map', {
      zoom: 7,
      center: [120.5, 29.5], // 江西省中心点
      viewMode: '2D'
    });
    
    // 根据视图类型显示不同的地图
    renderMapByViewType();
    
  } catch (error) {
    console.error('加载高德地图失败:', error);
  }
};

// 清除热力图实例
const clearHeatmap = () => {
  if (heatmapInstance) {
    heatmapInstance.setMap(null);
    heatmapInstance = null;
  }
};

// 根据视图类型渲染地图
const renderMapByViewType = () => {
  if (!amapInstance) return;
  
  // 清除所有覆盖物
  amapInstance.clearMap();
  
  // 确保热力图被清除
  clearHeatmap();
  
  // 获取筛选后的数据
  const filteredData = getFilteredGenealogyData();
  
  // 如果选择了特定地区，则将地图中心点移到该地区
  if (selectedRegion.value !== 'all' && filteredData.length > 0) {
    const regionData = filteredData[0];
    amapInstance.setZoomAndCenter(9, regionData.location);
  } else {
    // 恢复到全省视图
    amapInstance.setZoomAndCenter(7, [120.5, 29.5]);
  }
  
  if (mapViewType.value === 'marker') {
    // 渲染标记点
    const markerPositions = new Map(); // 用于记录已有的标记点位置
    
    filteredData.forEach(item => {
      // 检查是否有重叠位置，如果有则添加小偏移量
      const posKey = `${item.location[0]},${item.location[1]}`;
      let position = [...item.location];
      
      if (markerPositions.has(posKey)) {
        // 为重叠的点添加随机偏移
        const offset = 0.01; // 约1公里的偏移量
        position[0] += (Math.random() - 0.5) * offset;
        position[1] += (Math.random() - 0.5) * offset;
      }
      
      // 记录使用过的位置
      markerPositions.set(posKey, true);
      
      const marker = new AMap.Marker({
        position: position,
        title: item.name,
        label: {
          content: `<div class="marker-label">${item.name}</div>`,
          direction: 'top'
        }
      });
      
      // 创建信息窗口
      const infoWindow = new AMap.InfoWindow({
        content: `<div class="info-window">
          <h4>${item.name}</h4>
          <p>地区：${item.regionName}</p>
          <p>会员数量：${item.count}</p>
          <p>最近更新：${item.date}</p>
          <p>${item.description}</p>
        </div>`,
        offset: new AMap.Pixel(0, -30)
      });
      
      // 绑定点击事件
      marker.on('click', () => {
        infoWindow.open(amapInstance, marker.getPosition());
      });
      
      // 添加到地图
      amapInstance.add(marker);
    });
  } else if (mapViewType.value === 'heatmap') {
    // 渲染热力图
    const heatmapData = {
      max: 100,
      data: filteredData.map(item => {
        return {
          lng: item.location[0],
          lat: item.location[1],
          count: item.count * 10,
        };
      })
    };
    
    // 创建热力图实例
    heatmapInstance = new AMap.HeatMap(amapInstance, {
      radius: 25, // 热力图的半径
      opacity: [0, 0.8], // 热力图透明度范围
    });
    
    // 设置热力图数据
    heatmapInstance.setDataSet(heatmapData);
  }
};

// 地区变更处理函数
const onRegionChange = () => {
  renderMapByViewType();
};

// 监听视图类型变化
watch(mapViewType, () => {
  renderMapByViewType();
});

// 组件卸载前清理资源
onBeforeUnmount(() => {
  if (amapInstance) {
    amapInstance.destroy();
    amapInstance = null;
  }
  clearHeatmap();
});

// 组件挂载后初始化地图和加载数据
onMounted(() => {
  initMap();
  fetchGenealogyData(); // 获取家谱数据
});
</script>

<style lang="scss" scoped>
.dashboard-container {
  position: relative;
  padding: 24px;

  .github-corner {
    position: absolute;
    top: 0;
    right: 0;
    z-index: 1;
    border: 0;
  }

  .map-controls {
    display: flex;
    align-items: center;
    gap: 16px;

    .region-select {
      width: 120px;
    }

    .view-type-radio {
      margin-left: 8px;
    }
  }

  .map-container {
    width: 100%;
    height: 600px;
    border-radius: 4px;
  }
}

:deep(.marker-label) {
  padding: 2px 6px;
  background-color: white;
  border: 1px solid #ccc;
  border-radius: 4px;
  font-size: 12px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

:deep(.info-window) {
  padding: 8px;
  max-width: 280px;

  h4 {
    margin: 0 0 8px;
    font-size: 16px;
    color: var(--el-color-primary);
  }

  p {
    margin: 4px 0;
    font-size: 13px;
    line-height: 1.5;
  }
}
</style>
